
import base64
import json
import os
import re
import Utils
import Log
import time

cwd_root = os.getcwd() #运行根目录
dest_root = cwd_root + './publish' #输出单index文件目录
bin_root = cwd_root + './resources' #配置资源目录
pkt_root = cwd_root + '/src/web-mobile3.01' #源项目文件目录
stime = time.time()


def convert1(url, str1):
    with open(url, 'rb') as f1:
        return str1 + str(base64.b64encode(f1.read()), encoding='utf-8')
def convert2(url):
    #return ('%r' % Utils.fromFile(url))[1:-1]
    return Utils.fromFile(url)
resHandler = {
    '.json': lambda x: convert2(x),
    '.js': lambda x: convert2(x),
    '.wasm': lambda x: convert1(x, ''),
    '.png': lambda x: convert1(x, 'data:image/png;base64,'),
    '.jpg': lambda x: convert1(x, 'data:image/jpeg;base64,'),
    '.ttf': lambda x: convert1(x, ''),
    '.mp3': lambda x: convert1(x, ''),
    '.wav': lambda x: convert1(x, ''),
    '.bin': lambda x: convert1(x, '')
}
def folder2JsonRes(dir, filter='', resMap={}):
    for root, dirs, files in os.walk(dir):
        path = root.replace(filter, '', 1).replace('\\', '/')
        for f in files:
            url = '%s/%s' % (path, f)
            ext = os.path.splitext(f)[1]
            resMap[url] = resHandler[ext](root + '/' + f)
    return resMap

# load html
htmlContent = Utils.fromFile(pkt_root+'/index.html')
# clean html
htmlContent = re.sub(r'<script.*</script>', '', htmlContent)
htmlContent = re.sub(r'<!.*-->', '', htmlContent)
# style
styleContent = Utils.StyleScript(Utils.fromFile(pkt_root+'/style.css'))
htmlContent = htmlContent.replace(
    '<link rel="stylesheet" type="text/css" href="style.css"/>', styleContent, 1)

BODY = ""
BODY += Utils.fromFile(bin_root + '/engine-core.html')
BODY += Utils.fromFile(bin_root + '/ammo-core.html')

#用户业务逻辑
userLogicJsContent = Utils.fromFile(pkt_root +'/assets/main/index.js')
lock = False
keepContent = ''
tsArr = {}
assetDir = pkt_root + '/assets'
def handIndex(line: str):
    global lock
    if not lock:
        name = line.split(',', 1)[0][36:-1]
        if name.endswith('.ts'):
            line = line.replace('"cc"', '"./cc.js"', 1)
            tsArr[name] = line
        else:
            lock = True
    if lock:
        global keepContent
        keepContent += line

try:
    with open(assetDir+'/main/index.js', 'r', encoding='utf-8') as fp:
        for line in fp.readlines():
            if line != '\n':
                handIndex(line)
        launchJs = '<script>\n'
        logicJS = '<!-- Game Scripts. -->\n'
        for k, v in tsArr.items():
            logicJS += '<script id="%s">\n' % k+v+'</script>\n'
            launchJs += 'System.preload("./%s", getScriptById("%s"));\n' % (k, k)
        launchJs += '</script>'
except:
    Log.AppendLineTraceback()
finally:
    fp.close()

    for k, v in tsArr.items():
        name = './%s' % k
        keepContent = keepContent.replace(name, '../../%s' % k, 1)

    Utils.writeInFile(assetDir+'/main/index.js', keepContent)
    BODY += logicJS + launchJs + '\n'


#base64资源
jsonResMap = folder2JsonRes(pkt_root + '/cocos-js/assets', pkt_root + '/cocos-js/')
folder2JsonRes(assetDir, pkt_root + '/', jsonResMap)  # 资源文件夹
resContent = '<script>\nwindow.resMap = ' + json.dumps(jsonResMap, ensure_ascii=False) + '\n</script>'

#最终替换一次
htmlContent = htmlContent.replace(
    r'</canvas>', '</canvas>\n'+ BODY + resContent +'\n', 1)

#写入本地
Utils.writeInFile(dest_root+'/index.html', htmlContent)
Utils.writeInFile(pkt_root +'/assets/main/index.js', userLogicJsContent)

#导出日志
Log.AppendLineLog("useTime: " + str(round(time.time()-stime,2)))
Log.ExportLog()
